export interface LrcWord {
  start: number,
  duration: number,
  text: string
}

export interface LrcLine {
  start: number,
  duration: number,
  words: Array<LrcWord>,
  text: string
}

// 时间戳解析函数（返回毫秒）
function parseTimestamp(timestamp: string): number {
  const [min, sec] = timestamp.split(':');
  return parseFloat(min) * 60 * 1000 + parseFloat(sec) * 1000;
}

// 解析歌词字符串
export function parseLyrics(lyricsText: string,isAddFirstEmptyLine:boolean = true): LrcLine[] {
  const lines = lyricsText.trim().split('\n');
  const result: LrcLine[] = [];

  for (const line of lines) {
    // 忽略非歌词行
    if (!line.startsWith('[') || !line.match(/^\[\d{2}:\d{2}\.\d{2,3}\]/)) {
      continue;
    }

    // 匹配所有词的时间戳和文本
    //const wordRegex: RegExp = /\[(\d{2}):(\d{2})\.(\d{2,3})\]([^[\]]+)/g;
    const wordRegex = /(\[(\d{2}:\d{2}\.\d{2,3})\])([^\[]+)/g;
    const matches = [...line.matchAll(wordRegex)];

    if (matches.length === 0) {
      continue;
    }

    const wordTimes = matches.map(m => parseTimestamp(m[2])); // 毫秒
    const wordTexts = matches.map(m => m[3]); // 保留原始空格

    // 处理逐行歌词（仅一个时间戳）
    if (matches.length === 1) {
      // 提取行结束时间戳（行尾的 [时间戳]）
      const remaining = line.replace(wordRegex, '');
      const lineEndMatch = remaining.match(/^\[(\d{2}:\d{2}\.\d{2,3})\]$/);
      if (lineEndMatch?.length) {
        const lineEnd = parseTimestamp(lineEndMatch[1]);
        result.push({
          start: wordTimes[0],
          duration: 0, // 占位符，后续处理
          words: [{
            start: wordTimes[0],
            duration: lineEnd - wordTimes[0],
            text: wordTexts[0]
          }],
          text: wordTexts[0].trim(),
        });

      } else {
        result.push({
          start: wordTimes[0],
          duration: 0, // 占位符，后续处理
          words: [],
          text: wordTexts[0].trim(),
        });
      }
    }
    // 处理分词歌词（多个时间戳）
    else {
      // 提取行结束时间戳（行尾的 [时间戳]）
      const remaining = line.replace(wordRegex, '');
      const lineEndMatch = remaining.match(/^\[(\d{2}:\d{2}\.\d{2,3})\]$/);
      const lineEnd = lineEndMatch ? parseTimestamp(lineEndMatch[1]) : wordTimes[wordTimes.length - 1];

      // 构建歌词词对象
      const lyricsWords: LrcWord[] = [];
      for (let i = 0; i < wordTexts.length; i++) {
        const startTime = wordTimes[i];
        const endTime = i < wordTexts.length - 1
          ? wordTimes[i + 1]
          : lineEnd;
        const duration = endTime - startTime;

        lyricsWords.push({
          start: startTime,
          duration,
          text: wordTexts[i]
        });
      }

      // 构建歌词行对象（暂不计算 duration）
      result.push({
        start: wordTimes[0],
        duration: 0, // 占位符，后续处理
        words: lyricsWords,
        text: wordTexts.join('').trim()
      });
    }
  }

  // 处理行间衔接：插入空字符并计算 duration
  for (let i = 0; i < result.length; i++) {
    const currentLine = result[i];
    const nextLine = i < result.length - 1 ? result[i + 1] : null;

    // 计算当前行的 duration
    if (nextLine) {
      currentLine.duration = nextLine.start - currentLine.start;
    } else {
      // 无下一行，使用最后一个词的 end - start 或行尾时间戳
      if (currentLine.words.length > 0) {
        const lastWord = currentLine.words[currentLine.words.length - 1];
        currentLine.duration = lastWord.start + lastWord.duration - currentLine.start;
      } else {
        // 逐行歌词无分词，duration 为 0（或可自定义为固定值）
        currentLine.duration = 0;
      }
    }

    // 插入空字符（若下一行起始时间 > 当前行最后一个词的 end）
    if (nextLine && currentLine.words.length > 0) {
      const currentLastWord = currentLine.words[currentLine.words.length - 1];
      const currentLastEnd = currentLastWord.start + currentLastWord.duration;
      const nextFirstStart = nextLine.start;

      if (nextFirstStart > currentLastEnd) {
        const gapDuration = nextFirstStart - currentLastEnd;
        const emptyWord: LrcWord = {
          start: currentLastEnd,
          duration: gapDuration,
          text: '',
        };
        currentLine.words.push(emptyWord);
      }
    }
  }
  if(isAddFirstEmptyLine && result.length && result[0].start > 0){
    result.splice(0,0,{start:0,duration:result[0].start,words:[],text:''})
  }
  return result;
}

